<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票类型" prop="invoiceType">
        <el-select v-model="queryParams.invoiceType" placeholder="请选择发票类型" clearable>
          <el-option label="收据" value="收据" />
          <el-option label="普通发票" value="普通发票" />
          <el-option label="专用发票" value="专用发票" />
          <el-option label="红字普通发票" value="红字普通发票" />
          <el-option label="红字专用发票" value="红字专用发票" />
        </el-select>
      </el-form-item>
      <el-form-item label="开票人" prop="invoicePerson">
        <el-input
          v-model="queryParams.invoicePerson"
          placeholder="请输入开票人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票抬头" prop="invoiceHeader">
        <el-input
          v-model="queryParams.invoiceHeader"
          placeholder="请输入发票抬头"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票代码" prop="invoiceCode">
        <el-input
          v-model="queryParams.invoiceCode"
          placeholder="请输入发票代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发票号码" prop="invoiceNumber">
        <el-input
          v-model="queryParams.invoiceNumber"
          placeholder="请输入发票号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xs:salesInvoice:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['xs:salesInvoice:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="salesInvoiceList" border>
      <el-table-column label="发票号码" align="center" prop="invoiceNumber">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleView(scope.row)"
            v-hasPermi="['xs:salesInvoice:query']"
          >{{scope.row.invoiceNumber}}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="发票代码" align="center" prop="invoiceCode" />
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="发票金额" align="center" prop="invoiceValue" />
      <el-table-column label="发票类型" align="center" prop="invoiceType" />
      <el-table-column label="开票人" align="center" prop="invoicePerson" />
      <el-table-column label="开票日期" align="center" prop="invoiceDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.invoiceDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

<!--      <el-table-column label="发票抬头" align="center" prop="invoiceHeader" />-->
<!--      <el-table-column label="纳税人识别号" align="center" prop="taxpayerNumber" />-->
<!--      <el-table-column label="地址" align="center" prop="address" />-->
<!--      <el-table-column label="开户行" align="center" prop="openingBank" />-->
<!--      <el-table-column label="开户账号" align="center" prop="openAccount" />-->
<!--      <el-table-column label="发票状态" align="center" prop="invoiceStatus" />-->
<!--      <el-table-column label="备注" align="center" prop="remark" />-->

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['xs:salesInvoice:edit']"
            v-if="scope.row.invoiceStatus === '未确认'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['xs:salesInvoice:remove']"
            v-if="scope.row.invoiceStatus === '未确认'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售发票对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户ID" prop="clientId" style="display: none;">
              <el-input v-model="form.clientId" placeholder="请输入客户ID" />
            </el-form-item>
            <el-form-item label="客户编码" prop="clientCode" style="display: none;">
              <el-input v-model="form.clientCode" placeholder="请输入客户编码" />
            </el-form-item>
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" readonly>
                <el-button
                  slot="append"
                  @click="handleSelectClient"
                  icon="el-icon-search"
                  v-if="optType === 'add'"
                >
                </el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected" ></ClientSelect>
            </el-form-item>
            <el-form-item label="客户简称" prop="clientNick" style="display: none;">
              <el-input v-model="form.clientNick" placeholder="请输入客户简称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票人" prop="invoicePerson">
              <el-input v-model="form.invoicePerson" placeholder="请输入开票人" :readonly="optType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select v-model="form.invoiceType" placeholder="请选择发票类型" :disabled="optType === 'view'">
                <el-option label="收据" value="收据" />
                <el-option label="普通发票" value="普通发票" />
                <el-option label="专用发票" value="专用发票" />
                <el-option label="红字普通发票" value="红字普通发票" />
                <el-option label="红字专用发票" value="红字专用发票" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开票日期" prop="invoiceDate">
              <el-date-picker
                clearable
                v-model="form.invoiceDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开票日期"
                :disabled="optType === 'view'"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center" class="custom-divider">开票信息</el-divider>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票抬头" prop="invoiceHeader">
              <el-input v-model="form.invoiceHeader" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="纳税人识别号" prop="taxpayerNumber">
              <el-input v-model="form.taxpayerNumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开户行" prop="openingBank">
              <el-input v-model="form.openingBank" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户账号" prop="openAccount">
              <el-input v-model="form.openAccount" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票代码" prop="invoiceCode">
              <el-input v-model="form.invoiceCode" placeholder="请输入发票代码" :readonly="optType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发票号码" prop="invoiceNumber">
              <el-input v-model="form.invoiceNumber" placeholder="请输入发票号码" :readonly="optType === 'view'" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发票金额" prop="invoiceValue">
              <el-input v-model="form.invoiceValue" readonly/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="发票上传" prop="url">
              <FileUpload
                :limit="1"
                :fileSize="50"
                :fileType="fileType"
                :value="fileList"
                :optType="optType"
                :isShowTip="false"
                @onUploaded="handleUploaded"
                @onRemoved="handleRemoved"
                :disabled="optType === 'view'"
              >
              </FileUpload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center" class="custom-divider" v-if="form.invoiceId !== null">发票明细</el-divider>
        <InvoiceLine
            ref="invoiceLine"
            :invoiceId="form.invoiceId"
            :clientId="form.clientId"
            :optType="optType"
            @update="updateInvoiceValueFromChild"
            v-if="form.invoiceId !== null"
        ></InvoiceLine>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" @click="handleConfirm" v-if="optType === 'edit'">提 交</el-button>
        <el-button type="primary" @click="submitForm" v-if="optType !== 'view'">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSalesInvoice,
  getSalesInvoice,
  delSalesInvoice,
  addSalesInvoice,
  updateSalesInvoice } from "@/api/mes/xs/salesInvoice";
import ClientSelect from "@/components/clientSelect/single.vue";
import InvoiceLine from "./line.vue";
import { getUserProfile } from "@/api/system/user";

export default {
  name: "SalesInvoice",
  components: {
    ClientSelect,
    InvoiceLine
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 销售发票表格数据
      salesInvoiceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        clientId: null,
        clientCode: null,
        clientName: null,
        clientNick: null,
        invoiceType: null,
        invoicePerson: null,
        invoiceDate: null,
        invoiceHeader: null,
        taxpayerNumber: null,
        address: null,
        openingBank: null,
        openAccount: null,
        invoiceCode: null,
        invoiceNumber: null,
        invoiceValue: null,
        invoiceStatus: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        clientName: [
          {required: true, message: "客户不能为空", trigger: "change"}
        ],
        invoicePerson: [
          {required: true, message: "开票人不能为空", trigger: "blur"}
        ],
        invoiceDate: [
          {required: true, message: "开票日期不能为空", trigger: "blur"}
        ],
        invoiceType: [
          {required: true, message: "发票类型不能为空", trigger: "change"}
        ],
        invoiceCode: [
          {required: true, message: "发票代码不能为空", trigger: "blur"}
        ],
        invoiceNumber: [
          {required: true, message: "发票号码不能为空", trigger: "blur"}
        ],
      },
      // 显隐开关
      optType: null,
      // 上传文件类型
      fileType: [
        // 文档类
        "pdf",
        // 图片类
        "jpg", "jpeg", "png", "gif", "bmp",
      ],
      // 上传文件列表
      fileList: [],
      // 当前登录用户
      user: null,
    };
  },
  created() {
    this.getList();
    this.getUser();
  },
  methods: {
    /** 查询销售发票列表 */
    getList() {
      this.loading = true;
      listSalesInvoice(this.queryParams).then(response => {
        this.salesInvoiceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        invoiceId: null,
        clientId: null,
        clientCode: null,
        clientName: null,
        clientNick: null,
        invoiceType: null,
        invoicePerson: null,
        invoiceDate: new Date(),
        invoiceHeader: null,
        taxpayerNumber: null,
        address: null,
        openingBank: null,
        openAccount: null,
        invoiceCode: null,
        invoiceNumber: null,
        invoiceValue: null,
        invoiceStatus: "未确认",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.fileList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.invoicePerson = this.user.nickName;
      this.open = true;
      this.title = "添加销售发票";
      this.optType = 'add';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const invoiceId = row.invoiceId || this.ids
      getSalesInvoice(invoiceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改销售发票";
        this.optType = 'edit'
      });
    },
    // 查看
    handleView(row) {
      this.reset();
      getSalesInvoice(row.invoiceId).then(response => {
        this.form = response.data;
        response.data.url === null ? this.fileList = [] : this.fileList = response.data.url.split(',');
        this.open = true;
        this.title = "查看销售发票";
        this.optType = 'view'
      });
    },
    /** 确定按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.invoiceId != null) {
            updateSalesInvoice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSalesInvoice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const invoiceIds = row.invoiceId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + row.invoiceCode + '"的销售发票？').then(function() {
        return delSalesInvoice(invoiceIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xs/salesInvoice/export', {
        ...this.queryParams
      }, `salesInvoice_${new Date().getTime()}.xlsx`)
    },
    handleSelectClient(){
      this.$refs.clientSelect.showFlag = true;
    },
    //客户选择弹出框
    onClientSelected(obj){
      if(obj !== undefined && obj !== null){
        this.form.clientId = obj.clientId;
        this.form.clientCode = obj.clientCode;
        this.form.clientName = obj.clientName;
        this.form.clientNick = obj.clientNick;
        this.form.invoiceHeader = obj.clientName;
        this.form.taxpayerNumber = obj.creditCode;
        this.form.address = obj.address;
        this.form.openingBank = obj.openBank;
        this.form.openAccount = obj.openAccount;
      }
    },
    // 提交
    handleConfirm() {
      const invoiceLineList = this.$refs.invoiceLine.getInvoiceLineList();
      if (!invoiceLineList || invoiceLineList.length === 0) {
        this.$modal.msgError("发票明细不能为空，请至少选择一条数据！");
        return false;
      }
      this.form.invoiceStatus = '已确认';
      updateSalesInvoice(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.open = false;
        this.getList();
      }).catch(() => {
        this.form.invoiceStatus = '未确认';
        this.getList();
      });
    },
    // 上传成功回调
    handleUploaded(data) {
      this.form.url = data;
    },
    // 删除成功回调
    handleRemoved(data) {
      this.form.url = data;
    },
    // 获取登录用户
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
      });
    },
    // 根据子组件更新发票金额
    async updateInvoiceValueFromChild() {
      // 获取子组件实例
      const lineComponent = this.$refs.invoiceLine;
      if (lineComponent && typeof lineComponent.getInvoiceLineList === 'function') {
        // 获取子组件中的 invoiceLineList 数据
        const list = lineComponent.getInvoiceLineList();

        // 计算 price 总和
        const total = list.reduce((sum, item) => sum + (parseFloat(item.price) || 0), 0);

        // 更新 invoiceValue
        this.form.invoiceValue = parseFloat(total.toFixed(2));
        updateSalesInvoice(this.form)
      }
    },

  }
};
</script>
<style scoped>
.custom-divider ::v-deep .el-divider__text {
  background-color: #fff;
  color: #409EFF;
  padding: 4px 12px;
  border-radius: 8px;
  border: 1px solid #409EFF;
}
.custom-divider{
  background-color: #409EFF;
}
</style>
